<template>
  <div >
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品订单</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div>

      <!--      订单编号-->
      <br>
      <el-col >
        <el-col :span="9">
          <template>
            <div class="block">
              <el-date-picker
                  v-model="timeRange"
                  @change="sendTimeRange"
                  value-format="yyyy-MM-dd"
                  align="left"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </div>

          </template>
        </el-col>
        <el-col  :span="6">
          <el-input
              placeholder="请输入搜索内容"
              v-model="input" @keyup.enter.native="selectByName">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
        <el-col :span="9" >
          <el-button type="warning" @click="selectByName">查询</el-button>
          <el-button style="margin-left: 200px" @click="exportExcelSelect">导出Excel</el-button>
<!--          <el-button style="margin-left: 20px" @click="exportAllData">导出全部数据</el-button>-->
        </el-col>
      </el-col>


      <template>
        <el-table
            :data="tableData"
            @selection-change="handleSelectionChange"
            style="width: 100%">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="房型" prop="roomType"  align="center"></el-table-column>
          <el-table-column label="房号" prop="roomNumber"  align="center"></el-table-column>
          <el-table-column label="用户名" prop="name"  align="center"></el-table-column>
          <el-table-column label="联系电话" prop="phoneNum"  align="center"></el-table-column>
          <el-table-column label="入住时间" prop="checkInDate" :formatter="formatDate"  align="center"></el-table-column>
          <el-table-column label="离店时间" prop="checkOutDate" :formatter="formatDate"  align="center"></el-table-column>
        </el-table>
        <!--预览弹窗表格-->
        <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
          <el-table
              :data="selectData"
              height="380px"
              id="selectTable"
              style="width: 100%">
            <el-table-column label="房型" prop="roomType"  align="center"></el-table-column>
            <el-table-column label="房号" prop="roomNumber"  align="center"></el-table-column>
            <el-table-column label="用户名" prop="name"  align="center"></el-table-column>
            <el-table-column label="联系电话" prop="phoneNum"  align="center"></el-table-column>
            <el-table-column label="入住时间" prop="checkInDate" align="center"></el-table-column>
            <el-table-column label="离店时间" prop="checkOutDate" align="center"></el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="exportExcel">确定保存</el-button>
          </div>
        </el-dialog>

      </template>

      <template>
        <div class="block">
          <br>
          <el-pagination
              @current-change="changePage"
              :page-size="pageSize"
              hide-on-single-page
              layout="total,  prev, pager, next, jumper"
              :current-page="currentPage"
              :total="total">
          </el-pagination>
        </div>
      </template>

    </div>

  </div>
</template>


<script>
import moment from "moment";
import axios from "axios";
import FileSaver from "file-saver";
import XLSX from "xlsx";
// import * as XLSX from 'xlsx/xlsx.mjs';

export default {


  data() {
    return {
      baseUrl:'http://localhost:29182/hotel/order',
      //全部订单行
      activeName: 'first',
      tableData:[],
      //表格中选中的数据
      selectData: [],
      selectWindow: false,
      allDataSelected: false,
      input:'',
      search: '',
      value1: '',
      value2: '',
      timeRange: [] // 新增的属性，用于保存时间区间

    };
  },
  methods: {
    //  通过用户名搜索订单  搜索功能
    selectByName(){
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = 'http://localhost:29182//hotel/order/selectbyname?name=' + this.input+'&page='+page;
      console.log('url = ' + url);
      axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          console.log("跳转成功");
        }
      });
    },

    //  时间查询方法
    sendTimeRange() {
      // 获取选择的时间区间
      /*   const start = this.timeRange[0];
    const end = this.timeRange[1];*/
      console.log("DATE:" + this.timeRange)
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = this.baseUrl+'/selectTime?page=' + page;
      console.log('url = ' + url);

      // 发送请求到后端
      this.axios.post(url, this.timeRange).then(response => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });

    },
    changePage(page) {
      //todo 需要在订单界面添加用户信息的字段
// todo  userid需要根据实际情况修改
      this.$router.replace('?&page=' + page);
      let orderStatus = 0;
      switch (this.activeName) {
        case 'first':
          orderStatus = 5
          break;
        case 'second':
          orderStatus = 0
          break;
        case 'five':
          orderStatus = 1
          break;
        case 'six':
          orderStatus = 2
          break;

        default:
          break;
      }
      this.loadGoodsList(orderStatus);
    },


    //导出全部数据  excel
    exportAllData() {
      if (this.tableData.length < 1) {
        this.$message.error('没有数据可导出！');
        return false;
      }
      if (this.allDataSelected) {
        this.selectData = this.tableData;
      } else {
        this.selectData = [];
      }
      this.selectWindow = true;
    },

    //格式化数据
    getExcel(dom, title = '默认标题',) {
      var excelTitle = title;
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" });
      try {
        FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            excelTitle + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    //导出
    exportExcel() {
      this.getExcel('#selectTable', '导出的自定义标题')
    },
    //显示预览弹窗
    exportExcelSelect() {
      if (this.selectData.length < 1) {
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      if (this.selectData.length === this.tableData.length) {
        this.allDataSelected = true;
      } else {
        this.allDataSelected = false;
      }
      this.selectWindow = true;
    },
    //选中数据
    handleSelectionChange(val) {
      this.selectData = val;
    },

    //  日期转换格式
 /*   formatDate(row, column) {
      const options = { year: 'numeric', month: 'long', day: 'numeric' };
      return new Date(date).toLocaleDateString(undefined, options);
      // return moment(row.date).utcOffset(8).format('YYYY-MM-DD');
    },*/

    // 加载商品列表
    loadGoodsList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      // let url = 'http://localhost:29182//hotel/order/select?page='+page;
      let url = this.baseUrl+'/selectOrder?orderStatus=5&page=' + page;

      console.log('url = ' + url);

      axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },




    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
  },
  mounted() {
    this.loadGoodsList(5);

  }

};
</script>
